﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http.Headers;

namespace _06_MES_请求数据库
{
    public partial class Form1 : Form
    {
        Random rd = new Random();
        BindingList<User> users = new BindingList<User>();
        public Form1()
        {
            InitializeComponent();
            //绑定数据源
            dataGridView1.DataSource = users;
            //禁止修改表格的高度
            dataGridView1.AllowUserToResizeRows = false;
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            var clientHandler = new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
            };
            var client = new HttpClient(clientHandler);
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri("http://cjh1.ddnsto.net:7221/GetUser/GetAllUsers"),
                Headers =
    {
        { "accept", "*/*" },
        { "Accept", "*/*" },
        { "User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0" },
        { "Connection", "keep-alive" },
    },
            };
            using (var response = await client.SendAsync(request))
            {
                response.EnsureSuccessStatusCode();
                var body = await response.Content.ReadAsStringAsync();
                //将boyd的json字符串转换为对象集合：Newtonsoft.Json.JsonConvert(将JSON格式字符串转换)
                List<User> users = Newtonsoft.Json.JsonConvert.DeserializeObject<List<User>>(body);
                //清空绑定表格中的数据
                this.users.Clear();
                //将对象集合添加到绑定表格中
                foreach (var user in users)
                {
                    this.users.Add(user);
                }
            }
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            //获取选中的行的对象，将对象转换为User类型以供传递给我们的API
            User user = this.dataGridView1.CurrentRow.DataBoundItem as User;
            //判断是否选中行
            if (user == null)
            {
                MessageBox.Show("请选中一行数据");
                return;
            }

            var clientHandler = new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
            };
            var client = new HttpClient(clientHandler);
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Delete,
                RequestUri = new Uri("http://cjh1.ddnsto.net:7221/GetUser/DeleteUser?id="+ user.ID),
                Headers =
                {
                    { "accept", "*/*" },
                    { "Accept", "*/*" },
                    { "User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0" },
                    { "Connection", "keep-alive" },
                },
            };
            using (var response = await client.SendAsync(request))
            {
                response.EnsureSuccessStatusCode();
                var body = await response.Content.ReadAsStringAsync();
                MessageBox.Show(body);
            }
        }
        /// <summary>
        /// 随机生成用户信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button4_Click(object sender, EventArgs e)
        {
            Random rd = new Random();
            //随机生成用户信息
            User user = new User();
            user.ID = "";
            user.Name = "用户" + rd.Next(1, 1000).ToString();
            user.Password = "password-" + rd.Next(1, 99999999).ToString();
            user.Power = "普通用户";
            user.Remark = "随机对象";

            //赋值给空间，方便查看
            textBox1.Text = user.Name;
            textBox2.Text = user.Password;
            textBox3.Text = user.Power;
            textBox4.Text = user.Remark;

            //将对象转换成JSON格式的字符串
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(user);

            var clientHandler = new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
            };
            var client = new HttpClient(clientHandler);
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri("http://cjh1.ddnsto.net:7221/GetUser/AddUser"),
                Headers =
                {
                    { "accept", "*/*" },
                    { "Accept", "*/*" },
                    { "User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0" },
                    { "Connection", "keep-alive" },
                },
                Content = new StringContent(json)
                {
                    Headers =
                                        {
                                            ContentType = new MediaTypeHeaderValue("application/json")
                                        }
                }
            };
            using (var response = await client.SendAsync(request))
            {
                response.EnsureSuccessStatusCode();
                var body = await response.Content.ReadAsStringAsync();
                MessageBox.Show(body);
            }


        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button3_Click(object sender, EventArgs e)
        {
            var clientHandler = new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
            };
            var client = new HttpClient(clientHandler);
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri("http://cjh1.ddnsto.net:7221/GetUser/AddUser"),
                Headers =
    {
        { "accept", "*/*" },
        { "Accept", "*/*" },
        { "User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0" },
        { "Connection", "keep-alive" },
    },
                Content = new StringContent("{\r\n  \"id\": \"\",\r\n  \"name\": \"" + this.textBox1.Text + "\",\r\n  \"password\": \"" + this.textBox2.Text + "\",\r\n  \"power\": " + this.textBox3.Text + ",\r\n  \"remark\": \"" + this.textBox4.Text + "\"\r\n}")
                {
                    Headers =
        {
            ContentType = new MediaTypeHeaderValue("application/json")
        }
                }
            };
            using (var response = await client.SendAsync(request))
            {
                response.EnsureSuccessStatusCode();
                var body = await response.Content.ReadAsStringAsync();
                Console.WriteLine(body);
            }
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button5_Click(object sender, EventArgs e)
        {
            //将修改的数据封装成对象
            User user = new User();
            user.ID = this.textBox9.Text;
            user.Name = this.textBox8.Text;
            user.Password = this.textBox7.Text;
            user.Power = this.textBox6.Text;
            user.Remark = this.textBox6.Text;

            //将对象转换成JSON格式的字符串
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(user);

            //发起请求
            var clientHandler = new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
            };
            var client = new HttpClient(clientHandler);
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Put,
                RequestUri = new Uri("http://cjh1.ddnsto.net:7221/GetUser/UpdateUser"),
                Headers =
                                    {
                                        { "accept", "*/*" },
                                        { "Accept", "*/*" },
                                        { "User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0" },
                                        { "Connection", "keep-alive" },
                                    },
                Content = new StringContent(json)
                {
                    Headers =
        {
            ContentType = new MediaTypeHeaderValue("application/json")
        }
                }
            };
            using (var response = await client.SendAsync(request))
            {
                response.EnsureSuccessStatusCode();
                var body = await response.Content.ReadAsStringAsync();
               MessageBox.Show(body);
            }

        }

        /// <summary>
        /// 点击表格的行，获取选中的行的信息然后更新到文本框中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //获取选中的行的对象，将对象转换为User类型以供传递给我们的API
            User user = this.dataGridView1.CurrentRow.DataBoundItem as User;
            //判断是否选中行
            if (user == null)
            {
                return;
            }
            //将选中的行的信息更新到文本框中
            this.textBox9.Text = user.ID;
            this.textBox8.Text = user.Name;
            this.textBox7.Text = user.Password;
            this.textBox6.Text = user.Power;
            this.textBox5.Text = user.Remark;

        }
    }
}
